package com.zebra.gateway.protocol;

import com.zebra.common.ZebraBaseMessage;
import com.zebra.gateway.session.Session;
import com.zebra.remoting.protocol.*;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import lombok.*;

@Data
@ToString(exclude={"flag",  "msgBuf", "message", "commandProfile", "logs"})
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class GatewayCommand implements RemotingCommand {

    private  int id;
    private short flag; //加密 = (short)(response.getCmd()^length^1616)
    private short length; // 包场

    private int cmd; //命令号
    private int state = 200; // 状态
    private long  token;  //token
    private long userId;  //userId  GW <--> TMS userId 必须保留 不然不知道消息是谁的
    private short gameId;  // 大厅消息传0
    private short reserve;  // 保留字段

    private ByteBuf msgBuf;	// 消息体
    private ZebraBaseMessage message;  //消息体message

    private CommandProfile commandProfile;
    private boolean logs; // true 表示不打印  false 表示打印


    @Override
    public ProcessorType getProcessorType() {
        return ProcessorType.valueOf(this.commandProfile.getProcessorType());
    }

    @Override
    public PoolType getPoolType() {
        return PoolType.valueOf(this.commandProfile.getPoolType());
    }

    @Override
    public CommandType getCommandType() {
        return CommandType.valueOf(this.commandProfile.getCommandType());
    }

    @Override
    public int cmd() {
        return this.cmd;
    }

    @Override
    public int requestId() {
        return this.id;
    }

    @Override
    public int addRequestId(int id) {
        return this.id = id;
    }


    public void messageEncoder(){
        this.release();
        this.msgBuf = PooledByteBufAllocator.DEFAULT.directBuffer();
        message.write( this.msgBuf);
        this.length = (short) (this.msgBuf.readableBytes() + 28);
        this.flag = (short)(this.cmd^this.length^1616);
    }

    public void byteBufEncoder(){
        this.length = (short) (this.msgBuf.readableBytes() + 28);
        this.flag = (short)(this.cmd^this.length^1616);
    }

    public void release(){
        if (this.msgBuf != null){
            this.msgBuf = null;
        }
    }

}
